<script setup lang="ts" name="SidebarItem">
import type { RouterRecord } from "~/global/record/RouterRecord";

const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  isNest: {
    type: Boolean,
    default: false
  },
  basePath: {
    type: String,
    default: ''
  }
})

const appStore = useAppStore();

const opened = computed(() => appStore.sidebar.opened);

const showChildren = ref<RouterRecord>({});

function isChild(routerItem: RouterRecord) {

  const showingChildrens = routerItem.children?.filter(item => item.meta?.title && !item.hidden) || [];

  // 没有子菜单时，展示父菜单
  if (!showingChildrens.length) {
    showChildren.value = routerItem;
    return true;
  }

  // 存在一个子菜单时，且父菜单没有title时，展示子菜单
  if (showingChildrens.length == 1 && !routerItem.meta?.title) {
    showChildren.value = showingChildrens[0];
    return true;
  }
  return false;
}


function resolvePath(routePath: string, routeQuery: string = '') {
  if (isExternal(routePath)) {
    return routePath
  }
  if (isExternal(props.basePath)) {
    return props.basePath
  }
  if (routeQuery) {
    let query = JSON.parse(routeQuery);
    return { path: getNormalPath(props.basePath + '/' + routePath), query: query }
  }
  return getNormalPath(props.basePath + '/' + routePath);
}

function hasTitle(router: RouterRecord) {
  let title = router?.meta?.title || ""
  if (title.length > 5) {
    return title;
  } else {
    return "";
  }
}

</script>

<template>
  <div v-if="!item.hidden">
    <template v-if="isChild(item)">
      <el-menu-item :index="resolvePath(showChildren.path)" :class="{ 'submenu-title-noDropdown': !isNest }">
          <icon-svg :iconName="showChildren.meta.icon" />
        <template #title><span class="menu-title" :title="hasTitle(showChildren)">{{ showChildren?.meta?.title }}</span>
        </template>
      </el-menu-item>
    </template>
    <el-sub-menu v-else ref="subMenu" :index="item.path" teleported>
      <template v-if="item.meta" #title>
        <icon-svg :iconName="item.meta.icon" />
        <span v-if="opened" class="menu-title" :title="hasTitle(item.meta.title)">{{ item.meta.title }}</span>
      </template>

      <sidebar-item
          v-for="(child, index) in item.children"
          :key="child.path + index"
          :is-nest="true"
          :item="child"
          :base-path="resolvePath(item.path)"
          class="nest-menu"
      />
    </el-sub-menu>
  </div>
</template>
